<template>
  <ga-modal
    v-model:visible="visible"
    title-align="start"
    :width="600"
    @close="handleCancel(formRef)"
  >
    <template #title>关联项目</template>
    <ga-spin style="width: 100%" :loading="loading">
      <ga-form ref="formRef" :model="formData">
        <ga-form-item
          field="projectId"
          label="ITPM项目"
          label-col-flex="75px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-cascader
            v-model="formData.projectId"
            :field-names="{ value: 'id', label: 'cfname', children: '_children' }"
            :options="itpmData"
            placeholder="请选择项目(支持多选/搜索)"
            multiple
            check-strictly
            allow-clear
            allow-search
          />
        </ga-form-item>
      </ga-form>
    </ga-spin>
    <template #footer>
      <ga-button @click="visible = false">取消</ga-button>
      <ga-button type="primary" @click="handleOk">确定</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, defineEmits, reactive } from "vue";
import { createIp } from "@/api/layer2subnet.ts";
import { Message } from "@garco-design/web-vue";
import { RULE } from "@/constant/validators";
import useLoading from "@/hooks/loading";
import { commonArchTree } from "@/api/auth.ts";
import { useRoute } from "vue-router";
import { getIpProjectList } from "@/api/layer2subnet";

const route = useRoute();
const { id } = route.params;
const { loading, setLoading } = useLoading(false);
const formRef = ref(null);
const formData = reactive({
  projectId: [],
});
const visible = ref(false);
const itpmData = ref([]);
const open = async () => {
  visible.value = true;
  setLoading(true);
  const { data } = await commonArchTree();
  itpmData.value = data;
  await fetchBindProjectData();
};
// 获取已绑定项目列表
const fetchBindProjectData = async () => {
  try {
    const { data } = await getIpProjectList({ limit: -1 }, id);
    const bindProject = data.items?.map((item) => item?.id);
    bindProject?.forEach((item) => {
      itpmData.value.forEach((el) => {
        if (el.id === item) {
          el.disabled = true;
        } else if (el?._children) {
          el._children?.forEach((k) => {
            if (k.id === item) {
              k.disabled = true;
            }
          });
        }
      });
    });
  } finally {
    setLoading(false);
  }
};
// 保存
const emits = defineEmits(["fetchData"]);
const handleOk = async () => {
  const res = await formRef.value?.validate();

  if (!res) {
    const projectIds = formData?.projectId?.map((item) => ({ projectId: item }));
    try {
      const { code } = await createIp(id, "project", projectIds);
      if (code === 20000) Message.success("操作成功");
      emits("fetchData");
    } finally {
      visible.value = false;
    }
  }
};
const handleCancel = (formEl) => {
  formEl.resetFields();
};
defineExpose({ open });
</script>

<style lang="scss" scoped></style>
